package org.opens.javaskill.design.apply;

import java.util.Random;
import java.util.stream.IntStream;

/**
 * 说明:
 * <pre>
 *     1. ReadWriteLock design pattern;
 *
 * </pre>
 * @Date 2020/9/7 22:13
 * @Created by 99126
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        final SharedData sharedData = new SharedData(10);
        IntStream.rangeClosed(1, 5).forEach(i -> {
            new ReaderWorker(sharedData).start();
        });

        IntStream.rangeClosed(1, 2).forEach(i -> {
            new WriterWorker(sharedData, "abcdefghijklmnopqrstuvwxyz").start();
        });
    }

}

class ReadWriteLock {

    /**
     * 当前有多少个线程正在读
     */
    private int readingReaders = 0;

    /**
     * 这个是描述想读但是读不了进入阻塞的线程数
     */
    private int waitingReaders = 0;

    /**
     * 当前正在写的线程的数量, 同一时刻只允许一个线程写.
     */
    private int writingWriters = 0;

    /**
     * 当前想写但是有线程在写导致写不了导致进入阻塞的线程数.
     */
    private int waitingWriters = 0;

    /**
     * 是否更偏向于写操作
     */
    private boolean preferWriter = true;

    public ReadWriteLock() {
        this(true);
    }

    public ReadWriteLock(boolean preferWriter) {
        this.preferWriter = preferWriter;
    }

    public synchronized void readLock() throws InterruptedException {
        // 只要进入这个方法, 则如果此时有写的线程, 将会使当前线程陷入阻塞.
        this.waitingReaders++;
        try {
            while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {
                this.wait();
            }
            // 执行到这里说明这个锁下没有线程在写了.
            this.readingReaders++;
        } finally {
            // 执行到这里说明程序执行结束了, 相当于是阻塞也结束了.
            this.waitingReaders--;
        }
    }

    public synchronized void readUnlock() {
        // 解锁使正在读的线程数减1, 然后唤醒这个锁下的其他线程
        this.readingReaders--;
        this.notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        this.waitingWriters++;
        try {
            // 这里是-> 读/写都会导致阻塞
            while (readingReaders > 0 || writingWriters > 0) {
                this.wait();
            }
            this.writingWriters++;
        } finally {
            this.waitingWriters--;
        }
    }

    public synchronized void writeUnLock() {
        this.writingWriters--;
        this.notifyAll();
    }

}

class SharedData {

    private final char[] buffer;

    private final ReadWriteLock lock = new ReadWriteLock();

    public SharedData(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            this.buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        try {
            lock.readLock();
        } finally {
            lock.readUnlock();
        }
        return doRead();
    }

    private char[] doRead() {
        char[] newBuffer = new char[this.buffer.length];
        for (int i = 0; i < this.buffer.length; i++) {
            newBuffer[i] = this.buffer[i];
        }
        slowly(50);
        return newBuffer;
    }

    private void slowly(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void write(char c) throws InterruptedException {
        try {
            lock.writeLock();
            doWrite(c);
        } finally {
            lock.writeUnLock();
        }
    }

    private void doWrite(char c) {
        for (int i = 0; i < this.buffer.length; i++) {
            this.buffer[i] = c;
            slowly(10);
        }
    }

}

class WriterWorker extends Thread {

    private static final Random random = new Random(System.currentTimeMillis());

    private final SharedData data;

    private final String filler;

    private int index = 0;

    public WriterWorker(SharedData data, String filler) {
        this.data = data;
        this.filler = filler;
    }

    @Override
    public void run() {
        try {
            while (true) {
                char c = nextChar();
                data.write(c);
                Thread.sleep(random.nextInt(1000));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private char nextChar() {
        char c = filler.charAt(index);
        index++;
        if ( index >= filler.length() ) {
            index = 0;
        }
        return c;
    }

}

class ReaderWorker extends Thread {

    private final SharedData data;

    public ReaderWorker(SharedData data) {
        this.data = data;
    }

    @Override
    public void run() {
        try {
            while (true) {
                char[] read = data.read();
                System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(read));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}